package com.qingcloud.adminbackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.f4b6a3.ulid.UlidCreator;
import com.qingcloud.adminbackend.base.AjaxResult;
import com.qingcloud.adminbackend.constant.WamingConstant;
import com.qingcloud.adminbackend.entity.equipment.EquipmentDTO;
import com.qingcloud.adminbackend.entity.equipment.OrderEquipmentDTO;
import com.qingcloud.adminbackend.entity.role.SysRole;
import com.qingcloud.adminbackend.entity.sysorder.*;
import com.qingcloud.adminbackend.entity.sysorg.SysOrg;
import com.qingcloud.adminbackend.entity.sysorg.SysOrgLogoDTO;
import com.qingcloud.adminbackend.entity.sysorg.SysUserModuleDTO;
import com.qingcloud.adminbackend.entity.sysorg.SysUserOrgDTO;
import com.qingcloud.adminbackend.entity.sysstation.SysStationMoDTO;
import com.qingcloud.adminbackend.entity.user.SysUser;
import com.qingcloud.adminbackend.entity.usergroup.SysUsergroup;
import com.qingcloud.adminbackend.entity.usergroup.SysUsergroupUser;
import com.qingcloud.adminbackend.entity.userrole.UserRoleVO;
import com.qingcloud.adminbackend.enums.UcRoleEnum;
import com.qingcloud.adminbackend.exception.WmCommonException;
import com.qingcloud.adminbackend.mapper.*;
import com.qingcloud.adminbackend.mapper.app.UserAppRoleMapper;
import com.qingcloud.adminbackend.service.ISysFunctionService;
import com.qingcloud.adminbackend.service.ISysOrderService;
import com.qingcloud.adminbackend.utils.CommonUtil;
import com.qingcloud.adminbackend.utils.StringUtil;
import com.qingcloud.base.remote.pojo.BusinessApp;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author liyuhong
 * @since 2018-12-20
 */
@Service
public class SysOrderServiceImpl extends ServiceImpl<SysOrderMapper, SysOrder> implements ISysOrderService {

    @Resource
    private SysOrderMapper sysOrderMapper;

    @Resource
    private SysFunctionMapper sysFunctionMapper;

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Resource
    private SysUserOrderMgrMapper sysUserOrderMgrMapper;

    @Resource
    private SysOrderEquipmentMapper sysOrderEquipmentMapper;

    @Resource
    private SysStationGroupMapper sysStationGroupMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserOrderStationmgrMapper sysUserOrderStationmgrMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUsergroupMapper sysUsergroupMapper;

    @Resource
    private SysUsergroupUserMapper usergroupUserMapper;

    @Resource
    private SysBusinessAppMapper sysBusinessAppMapper;
    @Resource
    private ISysFunctionService sysFunctionService;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private UserAppRoleMapper userAppRoleMapper;

    /**
     * 查询订单列表
     *
     * @param userId
     * @param sysOrder
     * @return
     */
    @Override
    public IPage<SysOrder> findSysOrderList(String userId, SysOrderPageDTO sysOrder) {
        Page<SysOrderPageDTO> page = new Page<>(sysOrder.getCurrentPage(), sysOrder.getPerPage());
        boolean isAdmin = false;
        //是否超管
        if (WamingConstant.ADMIN_USER_ID.equals(userId)) {
            isAdmin = true;
        }
        if (!isAdmin) {
            SysUser sysUser = sysUserMapper.selectById(userId);
            //登录用户为空
            if (sysUser == null) {
                return new Page<>();
            }
            //完全管理权限
            if (Integer.valueOf(1).equals(sysUser.getAdminFlag())) {
                isAdmin = true;
            }
        }
        //获取用户有权限的订单
        Set<String> orderIdSet = sysOrderMapper.findUserReadOrderId(userId, isAdmin);
        return sysOrderMapper.findSysOrderList(page, userId, sysOrder, orderIdSet);
    }

    public Set<String> parentFunctionIds(Set<String> set, Set<String> parentIds) {
        set = sysFunctionMapper.findParentIdByIds(set);
        if (!StringUtils.isEmpty(set) && set.size() > 0) {
            set.stream().forEach(it -> {
                parentIds.add(it);
            });
            parentFunctionIds(set, parentIds);
        }
        return parentIds;
    }

    /**
     * 添加修改订单
     *
     * @param sysOrder
     * @return
     */
    @Override
    public AjaxResult setSysOrder(SysOrder sysOrder) {
        Set<String> fIds = new HashSet<>();
        Set<String> mIds = new HashSet<>();
        if (StringUtils.isEmpty(sysOrder.getId())) {
            sysOrder.setId(UUID.randomUUID().toString().replace("-", ""));
            sysOrder.setContractId(UUID.randomUUID().toString().replace("-", ""));
            sysOrderMapper.addSysOrder(sysOrder);
            //添加合同
            sysOrderMapper.addSysContract(sysOrder);
        } else {
            sysOrderMapper.updateSysOrder(sysOrder);
            //更新合同
            sysOrderMapper.updateSysContract(sysOrder);
            List<String> orderIds = new ArrayList<>();
            orderIds.add(sysOrder.getId());
            //查询订单删除的功能
            fIds = sysFunctionMapper.getFunctionByOrderOrgId(sysOrder);
            if (fIds.size() > 0) {
                //查询功能下的子级
                Set<String> ids = sysFunctionMapper.findFunctionIdByParentIds(fIds);
                for (String id : ids) {
                    fIds.add(id);
                }
            }
            //删除订单关联功能
            sysOrderMapper.deleteOrderFunction(orderIds);
        }
        /*----------------------------------------------------------------*/
        List<String> orgIds = new ArrayList<>();
        List<String> orderIds = new ArrayList<>();
        if (!StringUtils.isEmpty(sysOrder.getOrgId())) {
            orgIds = sysOrgMapper.getOrgIdsByOrgId(sysOrder.getOrgId());
            List<Map> orderByOrgId = sysOrderMapper.findOrderByOrgId(sysOrder.getOrgId());
            orderByOrgId.stream().forEach(it -> {
                if (!StringUtils.isEmpty(it.get("id"))) {
                    orderIds.add(String.valueOf(it.get("id")));
                }
            });
        }
        Set<String> functionIds = sysOrder.getFunctionIds();
        //删除订单所选功能以外的功能
        if (orgIds.size() > 0) {
            if (fIds.size() > 0) {
                //删除客户及下级分支机构的功能
                sysFunctionMapper.deleteSysOrgFunctionByorgIds(orgIds, fIds);
                //删除客户相关联订单的功能
                sysFunctionMapper.deleteOrderFunctionByOrgId(orderIds, fIds);
                //删除客户下用户的指定功能
                List<SysUserOrgDTO> users = sysOrgMapper.findSysUserOrgByorgIds(orgIds);
                List<String> userIds = new ArrayList<>();
                users.stream().forEach(it -> {
                    userIds.add(it.getUserId());
                });
                sysFunctionMapper.deleteByUserFunctions(userIds, fIds);
            }
        }
        if (!StringUtils.isEmpty(functionIds) && functionIds.size() > 0) {
            sysOrderMapper.insertOrderFunction(functionIds, sysOrder);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "操作成功");
    }

    /**
     * 订单关联客户
     *
     * @param orderId
     * @param orgId
     * @return
     */
    @Override
    public AjaxResult toOrderOrg(String orderId, String orgId) {
        //关联客户
        sysOrderMapper.toOrderOrg(orderId, orgId);
        return new AjaxResult(WamingConstant.SUCCESS, null, "关联成功");
    }

    /**
     * 删除订单
     *
     * @param orderIds
     * @return
     */
    @Override
    public AjaxResult deleteOrder(List<String> orderIds) {
        Long num = sysOrderMapper.findOrderEquipments(orderIds);
        if (num != null && num > 0) {
            return new AjaxResult(WamingConstant.FAILURE, "所选订单下有设备不可删除");
        }
        //删除订单
        sysOrderMapper.deleteOrder(orderIds);
        //删除订单关联功能
        sysOrderMapper.deleteOrderFunction(orderIds);
        //删除订单管理权限表
        sysUserOrderMgrMapper.deleteUserOrderMgr(orderIds);
        //删除订单设备表
        sysOrderEquipmentMapper.deleteOrderEquipment(orderIds);
//        //用户数据质控订单表
//        sysUserOrderDataQualityMapper.deleteUserOrderDataQuality(orderIds);
//        //用户可查询监测点数据表
//        sysUserOrderRetrieveStationMapper.deleteUserOrderRetrieveStation(orderIds);
        return new AjaxResult(WamingConstant.SUCCESS, null, "删除成功");
    }

    /**
     * 订单内设备列表
     *
     * @param equipmentDTO
     * @return
     */
    @Override
    public IPage<OrderEquipmentDTO> findOrderEquipmentList(EquipmentDTO equipmentDTO) {
        Page<OrderEquipmentDTO> page = new Page<>(equipmentDTO.getCurrentPage(), equipmentDTO.getPerPage());
        //获取订单业务类型
        SysOrder sysOrder = this.baseMapper.selectById(equipmentDTO.getOrderId());
        Integer businessType = 1;
        if (sysOrder != null) {
            businessType = sysOrder.getBusinessType();
        }
        //获取订单内设备列表
        IPage<OrderEquipmentDTO> orderEquipmentList = this.baseMapper.findOrderEquipmentList(page, equipmentDTO, businessType);
        //拼装空间名称
        if (businessType != 2) {
            List<OrderEquipmentDTO> records = orderEquipmentList.getRecords();
            List<SysStationMoDTO> stationMos = sysStationGroupMapper.findStationMo();
            records.stream().forEach(it -> {
                if (!StringUtils.isEmpty(it.getMoId())) {
                    splitString(it, stationMos);
                }
            });
            orderEquipmentList.setRecords(records);
        }
        return orderEquipmentList;
    }

    public void splitString(OrderEquipmentDTO equipmentBO, List<SysStationMoDTO> stationMos) {
        List<String> list1 = new ArrayList<>();
        int z = 5;
        int num = (equipmentBO.getMoId().length() / 5) - 1;
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                list1.add(equipmentBO.getMoId().substring(0, equipmentBO.getMoId().length() - z));
                z = z + 5;
            }
        }
        list1.add(equipmentBO.getMoId());
        String capation = "";
        for (SysStationMoDTO it : stationMos) {
            if (list1.contains(it.getId())) {
                capation += it.getCapation() + "-";
            }
        }
        if (StrUtil.isNotBlank(capation)) {
            capation = capation.substring(0, capation.length() - 1);
        }
        equipmentBO.setAddr(capation);
    }

    /**
     * 订单详情查看
     *
     * @param orderId
     * @return
     */
    @Override
    public SysOrder findOrderById(String orderId) {
        SysOrder sysOrder = this.baseMapper.findOrderById(orderId);
        if (Objects.nonNull(sysOrder)) {
            sysOrder.setFunctionIds(sysFunctionMapper.getOrderFunctionIds(orderId));
            List<Map> orderByOrgId = sysOrderMapper.findOrderByOrgId(sysOrder.getOrgId());
            int size = orderByOrgId.size() - 1;
            sysOrder.setOrdernum(size > 0 ? size : 0);
        }
        return sysOrder;
    }

    @Override
    public SysOrder findOrderDetail(String id) {
        SysOrder sysOrder = this.baseMapper.findOrderById(id);
        if (Objects.isNull(sysOrder)) {
            throw new WmCommonException("未找到项目信息");
        }
        return sysOrder;
    }

    /**
     * 没有关联客户的订单
     *
     * @param businessTypeSet 业务种类集合
     * @return
     */
    @Override
    public List<Map> findOrderByBusinessType(Collection<Integer> businessTypeSet) {
        final List<Map> orderList = this.baseMapper.findOrderByBusinessType(businessTypeSet);
        //业务种类字典查询
//        List<SysBusinessTypeDTO> data = sysOrderMapper.getBusinessType();
//        Map<String, SysBusinessTypeDTO> businessTypeMap = data.stream().collect(Collectors.toMap(SysBusinessTypeDTO::getValue, o -> o));
//        for (Map map : orderList) {
//            Object businessType = map.get("business_type");
//            if (Objects.nonNull(businessType)) {
//                map.put("business_type", businessTypeMap.get(businessType.toString()).getName());
//            }
//        }
        return orderList;
    }

    /**
     * 已关联客户的订单
     *
     * @param orgId
     * @return
     */
    @Override
    public List<Map> findOrderByOrgId(String orgId) {
        final List<Map> orgOrderList = this.baseMapper.findOrderByOrgId(orgId);
        //业务种类字典查询
//        List<SysBusinessTypeDTO> data = sysOrderMapper.getBusinessType();
//        Map<String, SysBusinessTypeDTO> businessTypeMap = data.stream().collect(Collectors.toMap(SysBusinessTypeDTO::getValue, o -> o));
//        for (Map map : orgOrderList) {
//            Object businessType = map.get("business_type");
//            if (Objects.nonNull(businessType)) {
//                map.put("business_type", businessTypeMap.get(businessType.toString()).getName());
//            }
//        }
        return orgOrderList;
    }

    /**
     * 客户批量关联订单
     *
     * @param sysOrderBO
     */
    @Override
    public AjaxResult orgToOrders(SysOrderBO sysOrderBO) {
        SysOrg sysOrg = sysOrgMapper.selectById(sysOrderBO.getOrgId());
        if (sysOrg == null) {
            return new AjaxResult(WamingConstant.FAILURE, "客户不存在！");
        }
        Integer businessType = Integer.valueOf(sysOrg.getBusinessType());
        List<SysOrder> sysOrders = sysOrderMapper.selectBatchIds(sysOrderBO.getOrderIds());
        List<String> notOrder = new ArrayList<>();
        sysOrders.forEach(it -> {
            if (!businessType.equals(it.getBusinessType())) {
                notOrder.add(it.getOrderName());
            }
        });
        if (notOrder.size() > 0) {
            String orderIdJson = StringUtil.objectString(notOrder);
            return new AjaxResult(WamingConstant.FAILURE, "订单" + orderIdJson + "业务种类与客户不符合！");
        }
        List<String> deleteOrderByIds = sysOrderMapper.isDeleteOrderByIds(sysOrderBO.getOrderIds());
        if (deleteOrderByIds.size() > 0) {
            String orderIdJson = StringUtil.listToString(deleteOrderByIds);
            return new AjaxResult(WamingConstant.FAILURE, "订单" + orderIdJson + "不存在！");
        }
        List<String> ids = new ArrayList<>();
        ids.add(sysOrderBO.getOrgId());
        sysOrderMapper.updateSysOrderByOrgIds(ids);
        if (!StringUtils.isEmpty(sysOrderBO.getOrderIds()) && sysOrderBO.getOrderIds().size() > 0) {
            this.baseMapper.orgToOrders(sysOrderBO);
        }
        return new AjaxResult(WamingConstant.SUCCESS, null, "关联成功");
    }

    /**
     * 有写权限的订单【售前】
     *
     * @return
     */
    @Override
    public Set<SysUserOrderMgrDTO> getOrders(SysUserOrderMgrDTO sysUserOrderMgrDTO, boolean isAdmin) {
        if (isAdmin) {
            return this.baseMapper.getAllOrders(sysUserOrderMgrDTO);
        } else {
            return addSysUserOrderMgrDTO(sysUserOrderMgrDTO);
        }
    }

    public Set<SysUserOrderMgrDTO> addSysUserOrderMgrDTO(SysUserOrderMgrDTO sysUserOrderMgrDTO) {
        //可管理监测数据
        //  List<SysUserOrderMgrDTO> orders = this.baseMapper.getRetrieveOrders(sysUserOrderMgrDTO);
        //可管理设备管理数据
        List<SysUserOrderMgrDTO> dtos = this.baseMapper.getOrders(sysUserOrderMgrDTO);
        //可管理的数据
        // List<SysUserOrderMgrDTO> sysUserOrderMgrDTOS = this.baseMapper.dataQuality(sysUserOrderMgrDTO);
        //可管理客户下的订单
        List<SysUserOrderMgrDTO> orderdtos = sysOrgMapper.findSysUserOrgOrderByUserId(sysUserOrderMgrDTO);
        return CommonUtil.intersectionAll(dtos, orderdtos);
    }

    /**
     * 用户授权【运维】读写权限的订单
     *
     * @return
     */
    @Override
    public Set<SysUserOrderMgrDTO> findOrders(SysUserOrderMgrDTO sysUserOrderMgrDTO, boolean isAdmin) {
        if (isAdmin) {
            return this.baseMapper.getAllOrders(sysUserOrderMgrDTO);
        } else {
            return addSysUserOrderMgrDTO(sysUserOrderMgrDTO);
        }
    }

//    /**
//     * 用户所属【销售】的订单
//     *
//     * @param sysUserOrderMgrDTO
//     * @return
//     */
//    @Override
//    public List<SysUserOrderMgrDTO> subordinateOrders(SysUserOrderMgrDTO sysUserOrderMgrDTO) {
//        return this.baseMapper.subordinateOrders(sysUserOrderMgrDTO);
//    }

    /**
     * 用户已授权【运维】的订单
     *
     * @param sysUserOrderMgrDTO
     * @return
     */
    @Override
    public List<SysUserOrderMgrDTO> grantedOrders(SysUserOrderMgrDTO sysUserOrderMgrDTO) {
        return this.baseMapper.grantedOrders(sysUserOrderMgrDTO);
    }

//    /**
//     * 用户已选【数据质控】的订单
//     *
//     * @param sysUserOrderMgrDTO
//     * @return
//     */
//    @Override
//    public List<SysUserOrderMgrDTO> dataQuality(SysUserOrderMgrDTO sysUserOrderMgrDTO) {
//        return this.baseMapper.dataQuality(sysUserOrderMgrDTO);
//    }

    /**
     * 客户及分支机构对应的订单
     *
     * @param orgId
     * @return
     */
    @Override
    public List<Map> findOrderListByOrgId(String orgId) {
        return this.baseMapper.findOrderListByOrgId(orgId);
    }

    /**
     * 所有订单
     *
     * @return
     */
    @Override
    public List<SysUserModuleDTO> findOrderList() {
        return baseMapper.getOrderByOrgIds(null, null, null);
    }

    @Override
    public List<SysUserModuleDTO> findOrders(String businessType, String userId, boolean isAdmin) {
        //获取该用户的角色
        List<UserRoleVO> roles = sysUserRoleMapper.findRoleByUserId(userId);
        List<Integer> roleIds = new ArrayList<>();
        roles.forEach(it -> {
            roleIds.add(it.getId());
        });
        //管理的客户下的订单
        List<SysUserModuleDTO> orders = sysOrderMapper.findOrgMgrOrderByUserId(userId, isAdmin, businessType);
        List<String> idList = orders.stream().map(SysUserModuleDTO::getId).collect(Collectors.toList());
        //管理的订单
        List<SysUserModuleDTO> list = sysUserOrderStationmgrMapper.findOrderMgrBybusinessType(userId, businessType);
        for (SysUserModuleDTO dto : list) {
            if (!idList.contains(dto.getId())) {
                orders.add(dto);
            }
        }
        return orders;
    }

    /**
     * 用户业务种类下有权限的订单
     *
     * @return
     */
    @Override
    public Set<SysUserOrderMgrDTO> getOrdersByBusinessType(SysUserOrderRequest orderRequest, boolean isAdmin) {
        if (isAdmin) {
            return this.baseMapper.getAllOrdersByBusinessType(orderRequest);
        } else {
            SysUserOrderMgrDTO sysUserOrderMgrDTO = new SysUserOrderMgrDTO();
            sysUserOrderMgrDTO.setBusinessTypes(orderRequest.getBusinessTypes());
            sysUserOrderMgrDTO.setUserId(orderRequest.getUserId());

            //可管理的订单
            List<SysUserOrderMgrDTO> mgrOrders = this.baseMapper.getOrders(sysUserOrderMgrDTO);

            //可管理客户下的订单
            List<SysUserOrderMgrDTO> mgrOrgOrders = sysOrgMapper.findSysUserOrgOrderByUserId(sysUserOrderMgrDTO);
            Set<SysUserOrderMgrDTO> set = new HashSet(mgrOrders.size() + mgrOrgOrders.size());
            set.addAll(mgrOrders);
            set.addAll(mgrOrgOrders);
            return set;
        }

    }

    /**
     * 云平台注册默认订单
     */
    @Override
    public String registerOrder(String company, String orgId) {
        SysOrder order = sysOrderMapper.selectOne(Wrappers.<SysOrder>lambdaQuery().eq(SysOrder::getOrgId, orgId)
                .eq(SysOrder::getDeleteFlag, 0));
        if (Objects.nonNull(order)) {
            return order.getId();
        }
        order = new SysOrder();
        String id = UlidCreator.getMonotonicUlid().toString().toLowerCase();
        order.setId(id).setOrderName(company + "项目").setOrderType(1).setServiceType(3).setStartTime("2023-01-01")
                .setEndTime("2099-12-31").setBusinessType(5).setOrgId(orgId).setDeleteFlag(0)
                .setCreateBy("cloud").setCreateDt(LocalDateTime.now());
        sysOrderMapper.insert(order);
        return id;
    }

    public SysBusinessApp getSysBusinessAppByCode(Integer orign, String bizCode) {
        return sysOrderMapper.findByBizCode(orign, bizCode);
    }

    /**
     * 注册新应用
     */
    public void registerApp(BusinessApp businessApp) {
        if (businessApp.getBizCode() == null || businessApp.getOrigin() == null) {
            throw new RuntimeException("来源或业务编号不能为空");
        }
        SysBusinessApp orgingBusiness = sysOrderMapper.findByBizCode(businessApp.getOrigin(), businessApp.getBizCode());
        if (orgingBusiness != null) {
            //更新APP信息
            orgingBusiness.setName(businessApp.getName());
            orgingBusiness.setBizCode(businessApp.getBizCode());
            orgingBusiness.setType(businessApp.getType());
            orgingBusiness.setOrigin(businessApp.getOrigin());
            sysBusinessAppMapper.updateById(orgingBusiness);
            //其他组织安装应用
            String business = sysOrgMapper.findOrgAllBusiness(businessApp.getOrgId());
            boolean isSave = true;
            if (StrUtil.isNotBlank(business)) {
                for (String bi : business.split(",")) {
                    if (Integer.parseInt(bi) == orgingBusiness.getId()) {
                        //已经包含了
                        isSave = false;
                    }
                }
            }
            if (isSave) {
                List<SysOrgLogoDTO> orgLogoList = new ArrayList<>();
                SysOrgLogoDTO logoDTO = new SysOrgLogoDTO();
                logoDTO.setBusinessType(String.valueOf(orgingBusiness.getId()));
                logoDTO.setOrgId(businessApp.getOrgId());
                orgLogoList.add(logoDTO);
                this.sysOrgMapper.insertOrgLogo(orgLogoList);
                sysOrgMapper.updateOrgBusiness(business + "," + orgingBusiness.getId(), businessApp.getOrgId());
            }
        } else {
            orgingBusiness = new SysBusinessApp();
            BeanUtil.copyProperties(businessApp, orgingBusiness, true);
            sysBusinessAppMapper.insert(orgingBusiness);
            List<SysOrgLogoDTO> orgLogoList = new ArrayList<>();
            SysOrgLogoDTO logoDTO = new SysOrgLogoDTO();
            logoDTO.setBusinessType(String.valueOf(orgingBusiness.getId()));
            logoDTO.setOrgId(businessApp.getOrgId());
            orgLogoList.add(logoDTO);
            this.sysOrgMapper.insertOrgLogo(orgLogoList);
            //更新组织业务种类
            String business = sysOrgMapper.findOrgAllBusiness(businessApp.getOrgId());
            sysOrgMapper.updateOrgBusiness(business, businessApp.getOrgId());
            //默认组添加
            SysUsergroup sysUsergroup = new SysUsergroup();
            sysUsergroup.setAppId(Integer.parseInt(orgingBusiness.getBizCode()));
            sysUsergroup.setName(orgingBusiness.getName() + "默认组");
            sysUsergroup.setOrgId(businessApp.getOrgId());
            sysUsergroup.setDescription(orgingBusiness.getName() + "默认分组");
            sysUsergroup.setCreateDt(LocalDateTime.now());
            sysUsergroup.setCreateBy(orgingBusiness.getOwner());
            sysUsergroupMapper.insert(sysUsergroup);
            //拥有者角色
            SysUsergroupUser usergroupUser = new SysUsergroupUser();
            usergroupUser.setUserId(orgingBusiness.getOwner());
            usergroupUser.setAppId(Integer.parseInt(orgingBusiness.getBizCode()));
            usergroupUser.setRoleId(UcRoleEnum.OWNER.code);
            usergroupUser.setGroupId(sysUsergroup.getId());
            usergroupUser.setCreateBy(orgingBusiness.getOwner());
            usergroupUserMapper.insert(usergroupUser);
        }

    }

    @Transactional(rollbackFor = Throwable.class)
    public void deleteBusinessApp(Integer origin, String bizCode) {
        if (origin == null || bizCode == null) {
            throw new RuntimeException("来源或业务编号不能为空");
        }
        SysBusinessApp orgingBusiness = sysOrderMapper.findByBizCode(origin, bizCode);
        if (orgingBusiness != null) {
            String orgId = sysOrgMapper.findBusinessOrgId(orgingBusiness.getId());
            //删除业务应用 sys_business_app
            sysBusinessAppMapper.deleteById(orgingBusiness.getId());
            //删除组织应用关系 sys_org_business
            sysOrgMapper.deleteOrgBusByBusinessId(orgingBusiness.getId());
            //删除功能  sys_function
            sysFunctionService.deleteBusiFuncForce(orgingBusiness.getId());
            //删除业务角色  sys_role
            QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("business_type", orgingBusiness.getId());
            sysRoleMapper.delete(roleQueryWrapper);
            //删除应用下成员
            sysUsergroupMapper.delete(Wrappers.<SysUsergroup>lambdaQuery().eq(SysUsergroup::getAppId, Integer.parseInt(bizCode)));
            usergroupUserMapper.delete(Wrappers.<SysUsergroupUser>lambdaQuery().eq(SysUsergroupUser::getAppId, Integer.parseInt(bizCode)));

            //更新组织业务种类
            if (StrUtil.isNotBlank(orgId)) {
                String business = sysOrgMapper.findOrgAllBusiness(orgId);
                sysOrgMapper.updateOrgBusiness(business, orgId);
            }
        }
    }

}
